package cur.nature.component.quartz.service;

import cur.nature.framework.mvc.crud.CrudService;
import cur.nature.component.quartz.dao.Component_QuartzDao;
import cur.nature.component.quartz.dao.Component_QuartzLogDao;
import cur.nature.component.quartz.model.Component_QuartzLogPO;
import cur.nature.component.quartz.model.Component_QuartzLogVO;
import cur.nature.component.quartz.model.Component_QuartzVO;
import cur.nature.tinyorm.core.bean.PageBean;
import cur.nature.framework.core.log.LOG;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 任务调度 Service
 * 作者：Auto Generator By wujian
 * 生成日期：2024-04-28 18:27:31
 */
@Service
@ConditionalOnProperty( value = {"cur.component.quartz.enable"})
public class Component_QuartzLogService extends CrudService<Component_QuartzLogPO, Component_QuartzLogVO, Component_QuartzLogDao> {
    public Component_QuartzLogService(Component_QuartzLogDao baseDao) {
        super(baseDao, Component_QuartzLogPO.class, Component_QuartzLogVO.class);
    }

    @Autowired
    private Component_QuartzDao quartzDao;

    public PageBean<Component_QuartzLogVO> list(Component_QuartzLogVO.list_Param param) throws Exception {
        PageBean<Component_QuartzLogVO> list = getDao().list(param);
        return list;
    }

    public Component_QuartzLogVO insertCust(String jobGroup, String jobCode, Date fireTime, int state, String msg) throws Exception {
        final Component_QuartzLogVO vo = new Component_QuartzLogVO();
        Component_QuartzVO quartzVO = quartzDao.getByCond(jobGroup, jobCode);
        if (quartzVO == null) {
            LOG.warn("调度id为空:" + jobGroup + ", " + jobCode);
            return null;
        }

        // 初始化
        vo.setSchedulerId(quartzVO.getId());
        vo.setOperateType(1);
        vo.setState(state + "");
        vo.setRunTime(fireTime);
        if (msg != null && msg.length() > 85) {
            msg = msg.substring(0, 82) + "...";
        }
        vo.setRemark(msg);
        // 删除非今天的日志
        if (state == -1) {
            getDao().deleteByDate(quartzVO.getId(), new Date());
        }
        // 保存运行日志
        getDao().save(vo);
        return vo;
    }

    public Component_QuartzLogVO updateCust(Component_QuartzLogVO vo, int state, String msg) throws Exception {
        if (vo == null) {return null;}
        // 初始化
        vo.setOperateType(2);
        vo.setState(state + "");
        vo.setEndTime(new Date());
        if (msg != null && msg.length() > 85) {
            msg = msg.substring(0, 82) + "...";
        }
        vo.setRemark(msg);
        // 保存运行日志
        getDao().save(vo);
        return vo;
    }
}

